package com.intersult.nutils.net.traffic;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import com.intersult.nutils.net.Streamer;

/**
 * The {@link TrafficStreamer} simulates heavy traffic on a stream.
 * 
 * @author Dieter Kaeppel
 * @date   16.11.2011
 */
public class TrafficStreamer extends Streamer {
	private final TrafficConfig config;

	public TrafficStreamer(InputStream inputStream, OutputStream outputStream, TrafficConfig config) {
		super(inputStream, outputStream);
		this.config = config;
	}

	@Override
	public void write(OutputStream outputStream, byte[] buffer, int length) throws IOException {
		if (config.isDebug())
			System.out.println("got " + length + " bytes");
		int segment = config.getMaxPackageLength() > 0 ? config.getMaxPackageLength() : length;
		for (int index = 0; index < length; index += segment) {
			if (config.getPackageDelay() > 0)
				try {
					Thread.sleep(config.getPackageDelay());
				} catch (InterruptedException exception) {
					throw new IOException(exception);
				}
			int writeLength = index + segment > length ? length - index : segment;
			outputStream.write(buffer, index, writeLength);
		}
	}
}